package com.fly.show.notepad.action;
//SaveAction.java

import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;

import com.fly.show.notepad.FileManager;
import com.fly.show.notepad.MainWindow;

public class SaveAction extends Action
{
    public SaveAction()
    {
        super();
        setText("保存(&S)");
        setToolTipText("保存文件");
        
        setImageDescriptor(ImageDescriptor.createFromFile(NewAction.class, "icons\\save.gif"));
    }
    
    @Override
    public void run()
    {
        final FileManager fileManager = MainWindow.getApp().getManager();
        if (!fileManager.isDirty())
        {
            return;
        }
        if (fileManager.getFileName() == null)
        {
            FileDialog saveDialog = new FileDialog(MainWindow.getApp().getShell(), SWT.SAVE);
            saveDialog.setText("请选择所要保存的文件");
            saveDialog.setFilterPath("F:\\");
            saveDialog.setFilterExtensions(new String[] {"*.java", "*.*"});
            String saveFile = saveDialog.open();
            if (saveFile != null)
            {
                fileManager.setFileName(saveFile);
                fileManager.setContent(MainWindow.getApp().getContent().getText());
                fileManager.save(fileManager.getFileName());
            }
            fileManager.setDirty(false);
            return;
        }
        if (fileManager.getFileName() != null)
        {
            MessageBox box = new MessageBox(MainWindow.getApp().getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
            box.setMessage("您确定要保存文件吗？");
            int choice = box.open();
            if (choice == SWT.NO)
            {
                return;
            }
            fileManager.setContent(MainWindow.getApp().getContent().getText());
            fileManager.save(fileManager.getFileName());
            fileManager.setDirty(false);
            return;
        }
    }
}